package com.yima.baseproj.config.validate.constraint.enumvalid;

import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author 一码
 * @description
 * @create 2021-01-29 11:12:33
 * @contact www.yanwei.xin 微信：13716343106 邮件：1424529270@qq.com
 **/
@Slf4j
public class EnumValidator implements ConstraintValidator<EnumValid, Object> {
    private final static String METHOD_NAME = "getName";
    private EnumValid annotation;

    @Override
    public void initialize(EnumValid constraintAnnotation) {
        annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        Class<?> cls = annotation.target();
        boolean ignoreEmpty = annotation.isNotEmpty();
        // target为枚举，并且value有值，或者不忽视空值，才进行校验
        if (cls.isEnum() && !ignoreEmpty) {
            return true;
        }
        boolean isCheck = cls.isEnum() && null != value;
        if (!isCheck) {
            return false;
        }
        boolean result = false;
        //获取枚举
        Object[] objects = cls.getEnumConstants();
        try {
            //获取方法
            Method method = cls.getMethod(METHOD_NAME);
            //循环枚举
            for (Object obj : objects) {
                //执行方法
                Object code = method.invoke(obj);
                //对比值
                if (Objects.deepEquals(value, code)) {
                    result = true;
                    break;
                }
            }
        } catch (Exception e) {
            log.error("EnumValidator call isValid() method exception", e);
        }
        return result;
    }
}
